package ae.pcfc.cldos.online.web.constraints;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import ae.pcfc.cldos.online.web.controller.client.company.nocandletters.NocAndLettersConstants;
import ae.pcfc.cldos.online.web.model.NocAndLettersModel;

/**
 * 
 * @author akhader
 *
 */
public class NOCLetterValidator implements ConstraintValidator<NOCLetterValidation, NocAndLettersModel> {

	
	
	public void initialize(NOCLetterValidation constraintAnnotation) {
		
	}

	public boolean isValid(NocAndLettersModel value,
			ConstraintValidatorContext context) {

		boolean result = true;
		
		String nocType = value.getNocAndLetters();
		List<String> reqFields = NocAndLettersConstants.NOC_FIELDS_MAPPING.get(nocType);
		if(reqFields!=null && reqFields.size()>0){
			for (Iterator<String> iterator = reqFields.iterator(); iterator.hasNext();) {
				String fieldName = (String) iterator.next();
						Method getter = null;
						try {
							getter = new PropertyDescriptor(fieldName, NocAndLettersModel.class).getReadMethod();
							Object valueObj = getter.invoke(value);
							if(valueObj==null || valueObj.toString().isEmpty()){
								 context.disableDefaultConstraintViolation();
							      context.buildConstraintViolationWithTemplate("message")
							          .addNode(fieldName)
							          .addConstraintViolation();
							      result = false;
							}
						} catch (IntrospectionException ise) {
							// TODO Auto-generated catch block
							ise.printStackTrace();
						}
						catch (IllegalAccessException iae) {
							// TODO Auto-generated catch block
							iae.printStackTrace();
						} catch (InvocationTargetException ite) {
							// TODO Auto-generated catch block
							ite.printStackTrace();
						}
			}
		}
		return result;
	}
	

}
